import React, { useImperativeHandle, useRef, useState } from 'react';
import { removeLocalStorageItem, intl } from '@/utils';
import Popup from 'devextreme-react/popup';
import Form, { SimpleItem } from 'devextreme-react/form';
import notify from 'devextreme/ui/notify';
import { deleteLocalItem, delProjectRequest, delZcbfInitRequest } from '../../tools/service';
import SpinLoading from '../SpinLoading';



const InputOKDialog = React.forwardRef((props: any, ref: any) => {
  const { refreshTable } = props;
  const [delPopupVisible, setDelPopupVisible] = useState<boolean>(false);
  const [dataID, setDataID] = useState<any>({});
  const [dataName, setDataName] = useState<any>({});
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [dataZcbfids, setDataZcbfids] = useState<any>([]);

  const oKDataForm = useRef<any>();
  const [formAllData, setFormAllData] = useState<any>({
    OKData: '',
  });

  useImperativeHandle(ref, () => ({
    show: (dataObj: any, dataname: any, zcbfids: any[] = []) => {
      setDelPopupVisible(true);
      setDataID(dataObj);
      setDataName(dataname);
      setDataZcbfids(zcbfids);
    },
  }));


  // 删除zcbf
  const delzcbfItem = async () => {
    setSpinLoad(true);
    const res = await delZcbfInitRequest(dataID);
    if (res.success) {
      notify({ message: `删除本地组成部分成功！`, position: 'top center', width: 300 }, "success", 1000);
      removeLocalStorageItem(dataID.zcbfid);
      setDelPopupVisible(false);
      refreshTable();
    } else {
      notify({ message: res.data, position: 'top center', width: 300 }, "error", 1000);
    }
    setSpinLoad(false);
  }
  // 删除项目
  const delProjectItem = async () => {
    setSpinLoad(true);
    const res = await delProjectRequest(dataID);
    if (res.success) {
      const resProject = await deleteLocalItem(dataID);
      if (resProject.success) {
        notify({ message: `删除本地项目成功！`, position: 'top center', width: 300 }, "success", 1000);
        setDelPopupVisible(false);
        refreshTable();
        if (dataZcbfids.length) {
          dataZcbfids.forEach((element: string) => {
            removeLocalStorageItem(element);
          });
        }
      } else {
        notify({ message: res.data, position: 'top center', width: 300 }, "error", 1000);
      }
    } else {
      notify({ message: res.data, position: 'top center', width: 300 }, "error", 1000);
    }
    setSpinLoad(false);
  }

  const validationRules = {
    OKData: [
      { type: 'required', message: '请输入OK后才能完成操作！' },
      {
        type: "async",
        message: "请输入OK后才能完成操作！",
        validationCallback: async (item: any) => {
          const result = item.value === 'OK';
          if (result) {
            return true;
          }
          return false;
        },
      },
    ]
  }

  return (
    <Popup
      {...props}
      width={600}
      height={320}
      dragOutsideBoundary={true}
      // resizeEnabled={true}
      visible={delPopupVisible}
      title={intl('pro.PopupModal.SelectComponent', '删除提醒')}
      hideOnOutsideClick={true}
      onHiding={() => {
        setDelPopupVisible(false);
        setFormAllData({
          OKData: ''
        });
      }}
      toolbarItems={[
        {
          widget: 'dxButton',
          toolbar: 'bottom',
          location: 'after',
          options: {
            text: intl('pub.cancel', '取消'),
            onClick: () => {
              setDelPopupVisible(false);
            }
          },
        },
        {
          widget: 'dxButton',
          toolbar: 'bottom',
          location: 'after',
          options: {
            text: intl('pub.ok', '确定'),
            type: 'default',
            validationGroup: "formAllDataData",
            onClick: async () => {
              if (oKDataForm.current) {
                const devForm: Form = oKDataForm.current as Form;
                const result: any = await devForm.instance.validate().complete;
                if (result && result.isValid && result.status === "valid") {
                  if (dataID.zcbfid) {
                    delzcbfItem();
                  } else {
                    delProjectItem();
                  }
                }
              }
            }
          },
        },
      ]}
      contentRender={() =>
        <>
          {spinLoad && <SpinLoading></SpinLoading>}

          <div>
            <div style={{ marginTop: 5, marginBottom: 10 }}>
              确认要删除项目
              <span style={{
                width: 200,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                wordBreak: 'break-all'
              }}>【{dataID.zcbfid ? dataID.zcbfid : dataID.projectBh}】{dataName}
              </span>吗？
            </div>
            <div style={{ color: 'red', marginBottom: 15, fontSize: 18, fontWeight: 600 }}>
              警告！ 此行为不可逆
            </div>
          </div>
          <div>
            <div style={{ marginBottom: 5 }}>
              确定要永久删除，请您输入OK！
            </div>
            <Form
              ref={oKDataForm}
              formData={formAllData}
              labelLocation={"left"}
              labelMode={"outside"}
              focusStateEnabled={true}
              readOnly={false}
              showColonAfterLabel={true}
              alignItemLabels={true}
            >
              <SimpleItem dataField="OKData" label={{ text: '输入OK' }} validationRules={validationRules.OKData} />
            </Form>
          </div>
        </>
      }
    />
  );
})

export default InputOKDialog;
